package com.uniledger.exchange.home.scheme;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.MenuItem;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import com.uniledger.commonlib.numberkeyboard.KeyboardUtil;
import com.uniledger.commonlib.util.ToastUtils;
import com.uniledger.exchange.HomeActivity;
import com.uniledger.exchange.R;
import com.uniledger.exchange.base.activity.BaseActivity;
import com.uniledger.exchange.contact.ContactFragment;
import com.uniledger.exchange.contact.UniContact;
import com.uniledger.exchange.home.HomeCenter;
import com.uniledger.exchange.home.scheme.fragment.transfer.OnTransferListener;
import com.uniledger.exchange.home.scheme.fragment.transfer.TransferIntoFragment;
import com.uniledger.exchange.model.HttpResult;
import com.uniledger.exchange.model.StellarAsset;
import com.uniledger.exchange.model.api.Api;
import com.uniledger.exchange.model.rx.RxException;
import com.uniledger.exchange.model.rx.RxProgress;
import com.uniledger.exchange.model.rx.RxSchedulers;
import com.uniledger.exchange.stellar.TransactionUtils;

import org.reactivestreams.Publisher;

import java.util.Map;

import butterknife.BindString;
import butterknife.BindView;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;

/**
 * 转账交易页面
 * <p>
 * 收款页面
 * <p>
 * 付款页面
 * <p>
 */
public class TransferActivity extends BaseActivity implements OnTransferListener {

    public static final int TRANSFER_PAY = 10;//我扫别人(扫码付款)
    public static final int TRANSFER_COLLECT = 20;//付款(别人扫我，扫码收款)
    public static final int TRANSFER_USER = 30;//直接选择用户转账

    KeyboardUtil keyboardUtil;

    private int flag = TRANSFER_USER;

    @BindView(R.id.container)
    FrameLayout container;

    UniContact uniContact;

    public static void start(Activity activity, int flag) {
        Intent intent = new Intent(activity, TransferActivity.class);
        intent.putExtra("Flag", flag);
        activity.startActivity(intent);
    }

    public static void start(Activity activity, StellarAsset stellarAsset) {
        Intent intent = new Intent(activity, TransferActivity.class);
        intent.putExtra("Flag", TRANSFER_COLLECT);
        intent.putExtra("StellarAsset", stellarAsset);
        activity.startActivity(intent);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_transfer);
    }

    @BindString(R.string.transfer_bar_title)
    String transfer_bar_title;

    @BindString(R.string.transfer_bar_pay_title)
    String transfer_bar_pay_title;

    @Override
    public void initBar() {
        super.initBar();
        if (flag == TRANSFER_PAY) {//扫码付款(主扫,个人)
            toolbar.setTitle(transfer_bar_pay_title);
        } else if (flag == TRANSFER_COLLECT) {//扫码收款(被扫，给我转账，谁扫谁操作)
            toolbar.setTitle(transfer_bar_title);
        } else {//用户转账
            toolbar.setTitle(transfer_bar_title);
        }
    }

    @Override
    public void getParams() {
        flag = getIntent().getIntExtra("Flag", TRANSFER_USER);
        StellarAsset stellarAsset = getIntent().getParcelableExtra("StellarAsset");
        if (flag == TRANSFER_PAY) {//扫码付款(主扫)
            uniContact = stellarAsset.contact;
            replaceFragment(TransferIntoFragment.newInstance(stellarAsset.contact, stellarAsset), "into");
        } else if (flag == TRANSFER_COLLECT) {//扫码收款(被扫)
            uniContact = stellarAsset.contact;
            replaceFragment(TransferIntoFragment.newInstance(stellarAsset.contact, stellarAsset), "into");
        } else {//用户转账
            ViewGroup.LayoutParams params = container.getLayoutParams();
            params.height = FrameLayout.LayoutParams.MATCH_PARENT;
            replaceFragment(ContactFragment.newInstance("", ""), "list");
        }
    }

    @Override
    public KeyboardUtil getKeyboard() {
        if (keyboardUtil == null) {
            keyboardUtil = new KeyboardUtil(this, false);
        }
        return keyboardUtil;
    }

    @Override
    public void transfer(Map<String, String> params) {

        if (flag == TRANSFER_USER) {
            //TODO 转账
            TransactionUtils.transaction(params.get("amount"), "Transfer", params.get("AccountId"))
                    .flatMap(new Function<String, Publisher<HttpResult<PayResult>>>() {
                        @Override
                        public Publisher<HttpResult<PayResult>> apply(String sign) throws Exception {
                            params.put("stellar_trx_sign", sign);
                            return Api.getService().doTransfer(params);
                        }
                    }).compose(RxSchedulers.io_main())
                    .compose(RxProgress.applyProgressBar(this))
                    .subscribe(new Consumer<HttpResult<PayResult>>() {
                        @Override
                        public void accept(HttpResult<PayResult> httpResult) throws Exception {
                            PayResult result = httpResult.data;
                            result.errorMessage = httpResult.msg;
                            result.setFlag(TransferActivity.this,HomeCenter.SCHEME_TRANSFER);
                            result.amount = params.get("amount");
                            if (httpResult.code == 0) {
                                PayOkActivity.start(TransferActivity.this, result);
                            }else {
                                PayFailActivity.start(TransferActivity.this, result);
                            }
                        }
                    }, new RxException<>(new Consumer<Throwable>() {
                        @Override
                        public void accept(Throwable throwable) throws Exception {
                            PayResult result = new PayResult(TransferActivity.this,HomeCenter.SCHEME_TRANSFER);
                            result.errorMessage = throwable.getMessage();
                            PayFailActivity.start(TransferActivity.this, result);
                        }
                    }));
        } else if (flag == TRANSFER_COLLECT) {
            TransactionUtils.transaction(params.get("amount"), "QR Transfer", params.get("AccountId"))
                    .flatMap(new Function<String, Publisher<HttpResult<PayResult>>>() {
                        @Override
                        public Publisher<HttpResult<PayResult>> apply(String sign) throws Exception {
                            params.put("stellar_trx_sign", sign);
                            return Api.getService().doPay(params);
                        }
                    })
                    .compose(RxSchedulers.io_main())
                    .compose(RxProgress.applyProgressBar(this))
                    .subscribe(new Consumer<HttpResult<PayResult>>() {
                        @Override
                        public void accept(HttpResult<PayResult> httpResult) throws Exception {
                            PayResult result = httpResult.data;
                            result.errorMessage = httpResult.msg;
                            result.setFlag(TransferActivity.this,HomeCenter.SCHEME_TRANSFER);
                            result.amount = params.get("amount");
                            if (httpResult.code == 0) {
                                PayOkActivity.start(TransferActivity.this, result);
                            } else {
                                PayFailActivity.start(TransferActivity.this, result);
                            }
                        }
                    }, new RxException<>(new Consumer<Throwable>() {
                        @Override
                        public void accept(Throwable throwable) throws Exception {
                            PayResult result = new PayResult(TransferActivity.this,HomeCenter.SCHEME_TRANSFER);
                            result.errorMessage = throwable.getMessage();
                            PayFailActivity.start(TransferActivity.this, result);
                        }
                    }));
        } else if (flag == TRANSFER_PAY) {

        }
    }


    @Override
    public void confirm() {

    }

    /**
     * 只有选择用户转账时，才回调此接口
     *
     * @param contact
     */
    @Override
    public void select(UniContact contact) {
        uniContact = contact;
        replaceFragment(TransferIntoFragment.newInstance(contact, null), "into");
    }

    @Override
    public void onBackPressed() {
        FragmentManager manager = getSupportFragmentManager();
        int count = manager.getBackStackEntryCount();

        if (count == 1) {
            HomeActivity.start(TransferActivity.this);
            finish();
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == android.R.id.home) {
            onBackPressed();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void replaceFragment(Fragment fragment, String name) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

        // Replace whatever is in the fragment_container view with this fragment,
        // and add the transaction to the back stack so the user can navigate back
        transaction.replace(R.id.container, fragment, name);
        transaction.addToBackStack(name);
        // Commit the transaction
        transaction.commit();
    }

    @Override
    public FrameLayout getContainer() {
        return container;
    }
}
